package com.wjw.java.io.writer_;

import java.io.FileWriter;
import java.io.IOException;

/**
 * 字符输出流InputStreamWriter之：
 * 文件输出流FileWriter
 */
public class FileWriter_ {

    public static void main(String[] args) {
        String filePath = "f:\\IO\\test_writer.txt";
        FileWriter writer = null;
        char [] chars = {'C','D','E','F','G'};
        String str = "你好啊,哈哈哈哈。";
        try {
            //writer = new FileWriter(filePath);
            writer = new FileWriter(filePath,true);//开启追加
            //write(int)：写入单个字符
            writer.write(65);//65对应的ASCII为A
            writer.write('B');//默认会将char转为int,
            //write(char[])：写入字符数组
            writer.write(chars);
            //write(char[],off,len)：写入字符数组指定长度部分
            writer.write(chars,0,2);
            //write(String)：写入字符串
            writer.write(str);
            //write(String,off,len)：写入字符串指定长度部分
            writer.write(str,0,str.length());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //对于FileWriter来说,需要调用flush()或close()方法,才能将内存中的数据,保存到文件中
            if(writer != null){
                try {
                    //writer.flush();
                    writer.close();//close() = flush() + 关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
